package com.carboy.launch.db;

import java.util.ArrayList;
import java.util.List;

import com.carboy.launch.BaseApplication;
import com.carboy.launch.activity.setting.DBWifiConfig;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;


/**
 * @author Administrator
 * 
 */
public class DbManager {

	/**
	 * 插入wifi配置
	 * 
	 * @param 
	 */
	public static void InsertWifiConfig(DBWifiConfig config) {
		synchronized (BaseApplication.getInstance().getDb()) {
			
				BaseApplication.getInstance().getInstance()
						.getDb()
						.execSQL(
								"INSERT INTO wifiConfig VALUES(?, ?, ?)",
								new String[] {config.getSsid(), config.getPassword(),
										config.getMode()});
			
		}
	}
	/**
	 * 查询wifi
	 * @param ssid
	 * @return
	 */
	
	public static DBWifiConfig GetWifiConfig(String ssid) {
		synchronized (BaseApplication.getInstance().getDb()) {
			DBWifiConfig config = new DBWifiConfig();
			Cursor c = BaseApplication
					.getInstance()
					.getDb()
					.rawQuery("SELECT * FROM wifiConfig where ssid like '%" + ssid + "%'",
							null);
			if (c != null && c.getCount() != 0) {
				for (int i = 0; i < c.getCount(); i++) {
					c.moveToPosition(0);
					config.setSsid( c.getString(0));
					config.setPassword( c.getString(1));
					config.setMode( c.getString(2));
				}
			}else{
				return null;
			}
			c.close();
			return config;
		}
	}
	
	/**
	 * 查询wifi
	 * @param ssid
	 * @return
	 */
	
	public static List<DBWifiConfig> GetWifiConfigs() {
		synchronized (BaseApplication.getInstance().getDb()) {
			List<DBWifiConfig> configs = new ArrayList<DBWifiConfig>();
			Cursor c = BaseApplication
					.getInstance()
					.getDb()
					.rawQuery("SELECT * FROM wifiConfig",
							null);
			if (c != null && c.getCount() != 0) {
				for (int i = 0; i < c.getCount(); i++) {
					c.moveToPosition(i);
					DBWifiConfig config = new DBWifiConfig();
					config.setSsid( c.getString(0));
					config.setPassword( c.getString(1));
					config.setMode( c.getString(2));
					configs.add(config);
				}
			}else{
				return null;
			}
			c.close();
			return configs;
		}
	}
	public static boolean deleWifi(String ssid) {
		synchronized (BaseApplication.getInstance().getDb()) {
			SQLiteDatabase db = BaseApplication
					.getInstance()
					.getDb();
			try {
				db.delete("wifiConfig","ssid="+ssid, null);
				return true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}finally {
				// 关闭数据库连接
				db.close();
			}
		}
	}


	/***
	 * 删除表 清空表中数据
	 * @param context
	 */
	public static void dropTable(Context context){
		DbHelper mDbHelper = new DbHelper(context);
		SQLiteDatabase db = mDbHelper.getReadableDatabase();

			db.delete("wifiConfig", null, null);
			if(db!=null){
				db.close();
			}
			
			if(mDbHelper!=null){
				mDbHelper.close();
			}
		
	}

}
